<?php

namespace app\api\service;


use app\api\library\Show;
use app\api\library\Domain;
use app\common\model\Shop;
use app\common\model\Third;
use app\common\model\UserGroup;
use fast\Http;
use app\common\library\Auth;
use fast\Random;
use think\Config;
use think\Db;
use app\common\model\User as UserModel;
use think\Exception;

class User
{
    /**
     * 根据code注册登录账号
     * @param $code
     * @param string $scene
     * @return array
     */
    public function getTokenByWxcode($code)
    {
        $msg = $this->getOpenIdByCode($code);
        if ($msg) {
            $auth = new Auth();
            if (isset($msg['openid'])) {
                $is_new = false;
                $user = \app\common\model\User::getByOpenid($msg['openid']);
                if ($user) {
                    if ($user->status != 'normal') {
                        return array('status'=>0, __('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $auth->direct($user->id);
                } else {
                    // 注册新用户并登录
                    do
                    {
                        $username = 'wx'.rand(100000,999999);
                        $res = \app\common\model\User::getByUsername($username);
                    }
                    while ($res);
                    Db::startTrans();
                    try {
                        $ret = $auth->register($username, Random::alnum(), '', '');
                        //写入thrid 扩展表
                        if ($ret){
                            $insData = [
                                'user_id' => $auth->id,
                                'openid'  =>  $msg['openid'],
                                'platform'=> 'wxapp'
                            ];
                            Third::create($insData);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return Show::error($e->getMessage());
                    }
                }
                if ($ret) {
                    $data = [
                        'token' =>   $auth->getToken()
                    ];
                    return Show::success($data);
                } else {
                    return Show::error($auth->getError());
                }
            } else {
                return Show::error($msg);
            }
        } else {
            return Show::error("获取失败");
        }
    }

    /**
     * 获取用户的展示信息
     * @param $auth Auth
     * @return mixed
     */
    public function getUserInfo($auth)
    {
        $user = $auth->getUser();
        $userInfo = $auth->getUserinfo();
        $userInfo['avatar'] = Domain::http($userInfo['avatar']);
        $userInfo['group_name'] = UserGroup::getName($userInfo['group_id']);
        $userInfo['person_auth'] = $user->profile ? $user->profile->certification_status : '';
        $userInfo['business_auth'] = $user->enterprise ? $user->enterprise->certification_status : '';
        $userInfo['is_auth'] = 1;
        return $userInfo;
    }

    public function getProfile($user_id)
    {
        try {
            $user = UserModel::get($user_id);
            if ($user->UserProfile && $user->UserProfile->status == $user->UserProfile->getCurrentTableConfig('status.success')){
                return true;
            }
        } catch (\Exception $e) {
            return false;
        }
        return false;
    }

    /**
     * 获取权限列表
     * @param $auth
     * @return array
     */
    public function getRuleActionList($auth)
    {
        $rule = $auth->getRuleList();
        foreach ($rule as $k=>$v) {
            if ($v['ismenu'] == 1) {
                unset($rule[$k]);
            } else {
                if (!strstr($v['name'],'api')) {
                    unset($rule[$k]);
                }else{
                    $rule[$k]['name'] = str_replace('api','', $v['name']);
                }
            }
        }
        $rule = array_column($rule, 'name');
        return $rule;
    }

    /**
     * 获取默认分组id
     * @return int|mixed
     * @throws \think\exception\DbException
     */
    public function getDefaultGroupId()
    {
        $default = UserGroup::get(['is_default'=>1]);
        if ($default){
            return $default->id;
        }
        return 0;
    }


    /**
     * code获取openid
     * @param $code
     * @return bool|mixed
     */
    public function getOpenIdByCode($code)
    {
        $config = config('wechat.mini_program');
        $config = $config['default'];
        $params = [
            'secret'     => $config['secret'],
            'appid'      => $config['app_id'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            if (!strpos($result['msg'], 'errcode')) {
                $msg = json_decode($result['msg'], true);
                return $msg;
            } else {
                return $result['msg'];
            }

        }
        return false;
    }
}